<template>
  <div>
    <el-form :model="formData" :rules="formRules" inline ref="formData" label-position="top" class="row-form">
      <el-card class="box-card">
        <div class="card-view">

          <div class="card-title">基础信息</div>

          <el-form-item label="房源名称:" prop="housingSource.name" class="form-item-css">
            <el-input v-model="formData.housingSource.name" placeholder="请输入"/>
          </el-form-item>

          <el-form-item label="价格:" prop="housingSource.univalenceDay" class="form-item-css">
            <el-input type="number" v-model="formData.housingSource.univalenceDay" placeholder="请输入"/>
          </el-form-item>

          <el-form-item label="面积:" prop="housingSource.housingArea" class="form-item-css">
            <el-input type="number" v-model="formData.housingSource.housingArea" placeholder="请输入"/>
          </el-form-item>

          <el-form-item label="地址" prop="housingSource.addressId" class="form-item-css">
            <el-cascader v-model="formData.housingSource.addressId" ref="cascader" :props="props" @change="handleChange"
                         style="width: 100%" :key="formData.housingSource.id"/>
          </el-form-item>

          <el-form-item label="详情地址" prop="housingSource.address" class="form-item-css">
            <el-input v-model="formData.housingSource.address" placeholder="请输入"></el-input>
          </el-form-item>

          <el-form-item label="门牌号" prop="housingSource.houseNumber" class="form-item-css">
            <el-input type="number" v-model="formData.housingSource.houseNumber"
                      placeholder="请输入"></el-input>
          </el-form-item>

          <el-form-item label="所属楼层" prop="housingSource.floor" class="form-item-css">
            <el-input type="number" v-model="formData.housingSource.floor"
                      placeholder="请输入"></el-input>
          </el-form-item>

          <el-form-item label="楼层总层数" prop="housingSource.totalFloor" class="form-item-css">
            <el-input type="number" v-model="formData.housingSource.totalFloor"
                      placeholder="请输入"></el-input>
          </el-form-item>

          <el-form-item label="是否可注册" prop="housingSource.whetherEnterprise" class="form-item-css">
            <el-radio-group v-model="formData.housingSource.whetherEnterprise">
              <el-radio label="0">是</el-radio>
              <el-radio label="1">否</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="使用率" prop="housingSource.utilizationRate" class="form-item-css">
            <el-input type="number" v-model="formData.housingSource.utilizationRate"
                      placeholder="请输入"></el-input>
          </el-form-item>

          <el-form-item label="工位" prop="housingSource.workCount" class="form-item-css">
            <el-input type="number" v-model="formData.housingSource.workCount"
                      placeholder="请输入"></el-input>
          </el-form-item>

          <el-form-item label="装修" prop="housingSource.fitmentCase" class="form-item-css">
            <el-input v-model="formData.housingSource.fitmentCase" placeholder="请输入"/>
          </el-form-item>

          <el-form-item label="支付" prop="housingSource.paymentMethod" class="form-item-css">
            <el-input v-model="formData.housingSource.paymentMethod" placeholder="请输入"/>
          </el-form-item>

          <el-form-item label="租期" prop="housingSource.leaseTerm" class="form-item-css">
            <el-input v-model="formData.housingSource.leaseTerm" placeholder="请输入"/>
          </el-form-item>

          <el-form-item label="房源标签" prop="housingSource.housingLabel" class="form-item-css">
            <el-input v-model="formData.housingSource.housingLabel" placeholder="请输入,多个 ; 隔开"/>
          </el-form-item>

          <el-form-item label="封面标签" prop="housingSource.coverLabel" class="form-item-css">
            <el-input v-model="formData.housingSource.coverLabel" placeholder="请输入,多个 ; 隔开"/>
          </el-form-item>

          <div class="form-item-css"></div>

          <el-form-item label="房源亮点" prop="housingSource.highlights" class="form-item-css">
            <el-input type="textarea" v-model="formData.housingSource.highlights" :autosize="{ minRows: 5 }"
                      placeholder="请输入"></el-input>
          </el-form-item>

          <div class="form-item-css"></div>
          <div class="form-item-css"></div>

          <el-form-item label="视频路径" prop="housingSource.videoPath" class="form-item-css">
            <div class="row-start">
              <div class="image-list" v-for="(item, index) in formData.videoArr">
                <video :src="item.video" class="image-item"></video>
                <div class="row-div image-hover">
                  <i class="el-icon-delete" @click="imageListDelete(item, index, 'videoArr')"></i>
                </div>
              </div>
              <UploadFile :file-list="formData.videoArr" listType fileType=".mp4,.mov"
                          @change="fileListChange($event, 'video')" style="margin-bottom: 10px;"/>
            </div>
          </el-form-item>

          <div class="form-item-css"></div>

          <el-form-item label="内容图片" prop="" style="width: 100%;">
            <div class="row-start" style="flex-wrap: wrap">
              <div class="image-list" v-for="(item, index) in formData.imageArr">
                <el-image :src="item.image" fit="cover" class="image-item"></el-image>
                <div class="row-div image-hover">
                  <i class="el-icon-delete" @click="imageListDelete(item, index, 'imageArr')"></i>
                </div>
              </div>
              <UploadFile multiple :file-list="formData.imageArr" listType @change="fileListChange($event, 'image')"
                          style="margin-bottom: 10px;"/>
            </div>
          </el-form-item>
        </div>
      </el-card>

      <el-card class="box-card">
        <div class="card-view">
          <div class="card-title">关联经纪人</div>
          <el-form-item label="经纪人姓名" prop="housingSource.housingAgentId" class="form-item-css">
            <el-select v-model="formData.housingSource.housingAgentId" filterable placeholder="请选择" style="width: 100%;"
                       @change="agentChange">
              <el-option v-for="item in brokerList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="经纪人UID" prop="housingSource.housingAgentId" class="form-item-css">
            <el-input v-model="formData.housingSource.housingAgentId"/>
          </el-form-item>
        </div>
      </el-card>

      <el-card class="box-card">
        <div class="card-view">
          <div class="card-title">所属者信息</div>
          <el-form-item label="类型" prop="housingSource.type" class="form-item-css">
            <el-radio-group v-model="formData.housingSource.type" @change="getGardenList('')">
              <el-radio :label="1">园区</el-radio>
              <el-radio :label="2">写字楼</el-radio>
              <el-radio :label="3">个人</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="园区" prop="housingSource.gardenId" class="form-item-css"
                        v-if="formData.housingSource.type == 1">

            <el-select v-model="formData.housingSource.gardenId" placeholder="请输入关键词" style="width: 100%;"
                       filterable remote reserve-keyword :remote-method="remoteMethod" :loading="loading">
              <el-option v-for="item in gardenList" :key="item.id" :label="item.gardenName"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="写字楼" prop="housingSource.gardenId" class="form-item-css"
                        v-if="formData.housingSource.type == 2">
            <el-select v-model="formData.housingSource.gardenId"  placeholder="请输入关键词" style="width: 100%;"
                       filterable remote reserve-keyword :remote-method="remoteMethod" :loading="loading">
              <el-option v-for="item in gardenList" :key="item.id" :label="item.gardenName"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="个人" prop="housingSource.housingMasterId" class="form-item-css"
                        v-if="formData.housingSource.type == 3">
            <el-select v-model="formData.housingSource.housingMasterId" filterable placeholder="请选择"
                       style="width: 100%;">
              <el-option v-for="item in housingSourceList" :key="item.id" :label="item.name"
                         :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </div>
      </el-card>

      <div class="row-div" style="margin: 30px 0">
        <el-button style="width: 300px" @click="$router.push('/housingManage/housingList')">取 消</el-button>
        <el-button type="primary" style="width: 300px" @click="onSubmit">提 交</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
  import { getProvinces } from '@/utils/common.js'

  export default {
    name: 'housingAdd',
    data() {
      return {
        isDisabled: false,
        detailId: null,
        detailState: 1,
        housingId: null, // 房产证ID
        gardenList: [],
        brokerList: [],
        housingSourceList: [],
        loading: false,
        formData: {
          housingSource: {
            address: null, // 详细地址
            addressId: null, // 省市区id
            city: null, // 市
            county: null, // 区
            coverLabel: null, // 封面标签 多标签隔开
            createTime: null, //
            delFlag: null, // 逻辑删除标记（0：显示；1：隐藏）
            fitmentCase: null, // 装修情况
            floor: null, // 所属楼层
            gardenId: null, // 园区id
            highlights: null, // 房源亮点
            houseNumber: null, // 门牌号
            housingAgentId: null, // 经纪人id
            agentName: null,
            agentPhone: null,
            housingArea: null, // 面积
            housingLabel: null, // 房源标签 多标签隔开
            housingMasterId: null, //
            housingMasterName: null, // 房东名称
            housingMasterPhone: null, // 房东手机号
            id: null, //
            latitude: null, // 纬度
            leaseTerm: null, // 租期
            longitude: null, // 经度
            name: null, // 房源名称
            paymentMethod: null, // 付款方式
            province: null, // 省
            rentStatus: null, // 租用状态：0未出租；1已出租（不能上架可以删除）；2正在出租
            shelfStatus: null, // 上架状态：0未上架；1上架
            totalFloor: null, // 楼层总层数
            type: 1, // 房源类型：1园区；2写字楼 3 个人
            univalenceDay: null, // 每平方每天价格
            utilizationRate: null, // 使用率
            whetherEnterprise: '0', // 是否可注册企业 0是 1否
            workCount: null // 工位数量
          },
          housingSourceImage: [],
          imageArr: [],
          videoArr: []
        },
        formRules: {
          'housingSource.name': [
            { required: true, message: '请输入房源名称', trigger: 'blur' }
          ],
          'housingSource.address': [
            { required: true, message: '请输入详细地址', trigger: 'blur' }
          ],
          'housingSource.addressId': [
            { required: true, message: '请选择省市区', trigger: 'blur' }
          ],
          'housingSource.coverLabel': [
            { required: true, message: '请输入封面标签', trigger: 'blur' }
          ],
          'housingSource.fitmentCase': [
            { required: true, message: '请输入装修情况', trigger: 'blur' }
          ],
          'housingSource.floor': [
            { required: true, message: '请输入所属楼层', trigger: 'blur' }
          ],
          'housingSource.highlights': [
            { required: true, message: '请输入房源亮点', trigger: 'blur' }
          ],
          'housingSource.houseNumber': [
            { required: true, message: '请输入门牌号', trigger: 'blur' }
          ],
          'housingSource.housingAgentId': [
            { required: true, message: '请选择经纪人id', trigger: 'blur' }
          ],
          'housingSource.housingArea': [
            { required: true, message: '请输入面积', trigger: 'blur' }
          ],
          'housingSource.housingLabel': [
            { required: true, message: '请输入房源标签', trigger: 'blur' }
          ],
          'housingSource.housingLabel': [
            { required: true, message: '请输入房源标签', trigger: 'blur' }
          ],
          'housingSource.leaseTerm': [
            { required: true, message: '请输入租期', trigger: 'blur' }
          ],
          'housingSource.paymentMethod': [
            { required: true, message: '请输入付款方式', trigger: 'blur' }
          ],
          'housingSource.type': [
            { required: true, message: '请选择类型', trigger: 'blur' }
          ],
          'housingSource.univalenceDay': [
            { required: true, message: '请输入价格', trigger: 'blur' }
          ],
          'housingSource.utilizationRate': [
            { required: true, message: '请输入使用率', trigger: 'blur' }
          ],
          'housingSource.workCount': [
            { required: true, message: '请输入工位数量', trigger: 'blur' }
          ]
        },
        props: getProvinces()
      }
    },
    beforeMount() {
      this.getBrokerList()
      this.getHousingMasterList()
      if (this.$route.query.detailId) {
        this.detailId = this.$route.query.detailId
        this.getHousingInfoRequest()
      }
    },
    methods: {
      remoteMethod(query) {
        if (!query) return []
        this.loading = true
        this.getGardenList(query)
      },
      /**
       * 关联经纪人
       * */
      agentChange(event) {
        const entity = this.brokerList.find(item => item.id == event)
        this.formData.housingSource.agentPhone = entity.phone
      },
      /**
       * 省市区变化事件
       */
      handleChange(row) {
        const entity = this.$refs.cascader.getCheckedNodes()[0]
        const list = entity && entity.pathLabels && entity.pathLabels.length > 0 ? entity.pathLabels : [null, null, null]
        let arr = ['province', 'city', 'county']
        for (let i = 0; i < list.length; i++) this.formData.housingSource[arr[i]] = list[i]
        console.log(this.formData.housingSource)
      },

      /**
       *  经纪人列表
       */
      async getBrokerList(str, type = 0) {
        const res = await this.$ajax.get(`/my/house/agent/search/list?sign=1`)
        this.brokerList = res.rows
      },
      /**
       * 园区列表
       */
      async getGardenList(value , gardenId = '') {
        this.gardenList = []
        if (!gardenId) {
          this.formData.housingSource.gardenId = null
          this.formData.housingSource.housingMasterId = null
          if (this.formData.housingSource.type == 3 || !value) return
        }
        const res = await this.$ajax.get(`/wx/entrust/backstage/gardenType/list?gardenType=${this.formData.housingSource.type}&gardenName=${value || ''}&gardenId=${gardenId}`).finally(() => this.loading = false)
        this.gardenList = res.rows
      },
      /**
       * 查询房东
       */
      async getHousingMasterList() {
        const res = await this.$ajax.get('/wx/entrust/backstage/housingMaster/list')
        this.housingSourceList = res.rows
      },
      async housingImageDelete(item, index) {
        if (this.detailId && this.detailState == 2) {
          await this.$ajax.get(`/linkwechat/image/remove?id=${item.id}`)
        }
        this.formData.housingSourceImage.splice(index, 1)
      },
      /**
       * 内容图片变化事件
       */
      async fileListChange(event, key) {
        if (this.detailId) {
          const res = await this.$ajax.post('/housing/sourceImage/add', {
            housingSourceId: this.detailId,
            [key]: event.pop()
          })
          return this.formData[`${key}Arr`].push(res.data)
        }
        this.formData[`${key}Arr`].push({ [key]: event.pop() })
      },
      async imageListDelete(item, index, key) {
        if (this.detailId) {
          await this.$ajax.get(`/housing/sourceImage/remove?id=${item.id}`)
        }
        this.formData[key].splice(index, 1)
      },
      onSubmit() {
        this.$refs.formData.validate(async(valid) => {
          if (!valid) return
          const formData = JSON.parse(JSON.stringify(this.formData))
          this.formData.housingSource.type == 3 ? formData.housingSource.gardenId = null : formData.housingSource.housingMasterId = null
          formData.housingSource.addressId = formData.housingSource.addressId.join(',')
          const url = this.formData.housingSource.id ? '/housing/source/backstage/update' : '/housing/source/backstage/add'
          formData.housingSourceImage = [...formData.imageArr, ...formData.videoArr]
          await this.$ajax.post(url, formData)
          this.$message.success('操作成功!')
          this.$router.push('/housingManage/housingList')
        })
      },
      /**
       * 房源详情
       */
      async getHousingInfoRequest() {
        const res = await this.$ajax.get(`/housing/source/backstage/info?id=${this.detailId}`)
        const imageArr = res.data.housingSourceImage.filter(item => item.image)
        const videoArr = res.data.housingSourceImage.filter(item => item.video)
        res.data.housingSource.addressId = res.data.housingSource.addressId?.split(',') || null
        res.data.videoArr = videoArr
        res.data.imageArr = imageArr
        this.formData = res.data
        this.getGardenList('', res.data.housingSource.gardenId)
      }
    }
  }
</script>

<style scoped lang="scss">
  .box-card + .box-card {
    margin-top: 20px;
  }

  .image-list {
    width: 148px;
    height: 148px;
    position: relative;
    margin-right: 10px;
    border: 1px dashed #c0ccda;
    border-radius: 6px;
    margin-bottom: 10px;
    &:hover > .image-hover {
      display: flex;
      z-index: 1;
    }
    .image-item, .image-hover {
      width: 100%;
      height: 100%;
      border-radius: 6px;
    }
    .image-hover {
      position: absolute;
      top: 0;
      left: 0;
      display: none;
      background: rgba(0, 0, 0, 0.5);
      color: white;
      font-size: 20px;
    }
  }

  .card-view {
    width: 100%;
    .card-title {
      width: 200px;
      font-weight: bold;
      font-size: 18px;
      padding-bottom: 10px;
      margin-bottom: 20px;
      position: relative;
      &:before {
        content: "";
        width: 200px;
        height: 1px;
        background: #000000;
        position: absolute;
        bottom: 0;
        left: 0;
      }
    }

    .form-item-css {
      width: calc(100% / 3 - 10px);
      position: relative;
      .delete-but {
        position: absolute;
        color: red;
        z-index: 2;
        right: 0;
        top: -40px;
      }
    }
  }

  .image-view {
    width: 100%;
    height: 178px;
    position: relative;
    .el-icon-circle-close {
      font-size: 30px;
      color: red;
      position: absolute;
      top: 10px;
      right: 10px;
      z-index: 100;
    }
    .el-icon-circle-close:hover {
      cursor: pointer;
    }
  }

</style>
